package com.xhwl.centiotdata.handler.device.impl;

import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.handler.device.DeviceIntegrationFactory;
import com.xhwl.centiotdata.handler.device.DeviceIntegrationHandler;
import com.xhwl.centiotdata.handler.pedestrian.PedestrianIntegrationFactory;
import com.xhwl.centiotdata.pojo.dto.bsedu.BseduDeviceDTO;
import com.xhwl.centiotdata.pojo.dto.dahua.DeviceDaHuaDTO;
import com.xhwl.centiotdata.pojo.dto.device.DeviceIntegrationConfigDTO;
import com.xhwl.centiotdata.pojo.dto.pedestrian.PedestrianIntegrationConfigDTO;
import com.xhwl.centiotdata.service.cent.IDeviceCentService;
import com.xhwl.centiotdata.service.cent.IDeviceProductService;
import com.xhwl.centiotdata.suppliersystem.bsedu.DeviceBseduHandler;
import com.xhwl.centiotdata.suppliersystem.dahua.DeviceDaHuaHandler;
import com.xhwl.common.dto.cent.device.DeviceDTO;
import com.xhwl.common.dto.cent.pedes.DeviceAttributeDTO;
import com.xhwl.common.enums.device.DeviceOnlineStatusEnum;
import com.xhwl.common.pojo.cent.device.Device;
import com.xhwl.common.pojo.cent.device.DeviceProduct;
import com.xhwl.common.pojo.cent.device.DeviceProductCategory;
import com.xhwl.common.pojo.cent.device.DeviceType;
import com.xhwl.common.query.cent.device.DeviceTypeQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @Author： wangyiling
 * @Description：拉取数字哨兵设备
 * @Date 2022/08/16/ 09:29
 */
@Service
public class DeviceIntegrationBseDuHandler  extends DeviceIntegrationHandler  {
    private static final Logger log = LoggerFactory.getLogger(DeviceIntegrationDaHuaHandler.class);

    @Autowired
    private DeviceBseduHandler deviceBseduHandler;

    @Autowired
    private IDeviceCentService deviceCentService;

    @Autowired
    private IDeviceProductService iDeviceProductService;

    // 数字哨兵系统类型名字
    private static final String CATEGORY_NAME = "数字哨兵";
    // 数字哨兵设备类型名字
    private static final String DEVICE_TYPE_NAME = "体温检测";

    @Override
    public void afterPropertiesSet() throws Exception {
        List<DeviceProduct> productList = iDeviceProductService.list();
        AtomicInteger productId = new AtomicInteger(51);
        for(DeviceProduct product : productList){
            if(product.getName().contains("数字哨兵")){
                productId.set(product.getId());
                break;
            }
        };
        DeviceIntegrationFactory.register(productId.get(), this);
    }

    @Override
    public void pullDevice(DeviceIntegrationConfigDTO configDTO) {
        if (configDTO.getDeviceType() == null) {
            log.error("projectId：{} pullDevice failed! deviceType is null!", configDTO.getProjectId());
            return;
        }
        // 拉取数据
        try {
            List<BseduDeviceDTO> deviceDaHuaDTOList = deviceBseduHandler.getDevice(getConfig(configDTO));
            if (CollectionUtils.isEmpty(deviceDaHuaDTOList)) {
                return;
            }
            // 转换数据
            List<DeviceDTO> deviceDTOList = this.handleDevice(configDTO, deviceDaHuaDTOList);
            // 存储业务中台
            deviceCentService.asyncUpdateDevice(deviceDTOList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    public void pullDeviceOnlineStatus(DeviceIntegrationConfigDTO configDTO) {
        if (configDTO.getDeviceType() == null) {
            log.error("projectId：{} pullDeviceOnlineStatus failed! deviceType is null!", configDTO.getProjectId());
            return;
        }
        try {
            // 拉取数据
            List<BseduDeviceDTO> deviceDaHuaDTOList = deviceBseduHandler.getDevice(getConfig(configDTO));
            if (CollectionUtils.isEmpty(deviceDaHuaDTOList)) {
                return;
            }
            // 转换数据
            List<Device> deviceList = this.handleDeviceOnlineStatus(configDTO, deviceDaHuaDTOList);
            // 存储业务中台
            deviceCentService.asyncUpdateOnlineStatus(deviceList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private PedestrianIntegrationConfigDTO getConfig(DeviceIntegrationConfigDTO configDTO){
        PedestrianIntegrationConfigDTO config = new PedestrianIntegrationConfigDTO();
        BeanUtils.copyProperties(configDTO, config);
        config.setOrgIndexCode(configDTO.getOrgCode());
        return config;
    }
    private List<DeviceDTO> handleDevice(DeviceIntegrationConfigDTO configDTO, List<BseduDeviceDTO> deviceDTOList) {
        List<DeviceProductCategory> categoryList = deviceCentService.listCategory();
        AtomicInteger categoryId = new AtomicInteger(1);
        for(DeviceProductCategory category : categoryList){
            if(category.getName().contains(CATEGORY_NAME)){
                categoryId.set(category.getId());
                break;
            }
        };
        List<DeviceType> deviceTypeList = deviceCentService.getDeviceTypes(new DeviceTypeQuery()).getResult();
        AtomicInteger deviceTypeId = new AtomicInteger(1);
        for(DeviceType deviceType : deviceTypeList){
            if(deviceType.getName().contains(DEVICE_TYPE_NAME)){
                deviceTypeId.set(deviceType.getId());
                break;
            }
        };
        return deviceDTOList.stream().map(deviceBseDTO -> {
            DeviceDTO deviceDTO = new DeviceDTO();
            deviceDTO.setProjectId(configDTO.getProjectId());
            deviceDTO.setProductId(configDTO.getProductId());
            deviceDTO.setCategoryId(categoryId.get());
            deviceDTO.setDeviceTypeId(deviceTypeId.get());
            deviceDTO.setName(deviceBseDTO.getDeviceName());
            deviceDTO.setThirdDeviceId("szsb"+deviceBseDTO.getDeviceId());
            deviceDTO.setOnlineStatus(deviceBseDTO.getStatus());
            return deviceDTO;
        }).collect(Collectors.toList());
    }

    private List<Device> handleDeviceOnlineStatus(DeviceIntegrationConfigDTO configDTO, List<BseduDeviceDTO> deviceDTOList) {
        List<DeviceType> deviceTypeList = deviceCentService.getDeviceTypes(new DeviceTypeQuery()).getResult();
        AtomicInteger deviceTypeId = new AtomicInteger(1);
        for(DeviceType deviceType : deviceTypeList){
            if(deviceType.getName().contains(DEVICE_TYPE_NAME)){
                deviceTypeId.set(deviceType.getId());
                break;
            }
        };
        return deviceDTOList.stream().map(deviceBseDTO -> {
            Device device = new Device();
            device.setProjectId(configDTO.getProjectId());
            device.setThirdDeviceId(deviceBseDTO.getDeviceId());
            device.setDeviceTypeId(deviceTypeId.get());
            device.setOnlineStatus(DeviceOnlineStatusEnum.getById(deviceBseDTO.getStatus()));
            return device;
        }).collect(Collectors.toList());
    }
}
